<?php
Class C_admin extends Cemvc_Control_Base
{
  private $common_names = array(
				"长子","次子","三子","四子","五子","六子","七子","八子","九子","十子","十一子","十二子","十三子","十四子","十五子","十六子","十七子","十八子","十九子","二十子",
			  	"长女","次女","三女","四女","五女","六女","七女","八女","九女","十女","十一女","十二女","十三女","十四女","十五女","十六女","十七女","十八女","十九女","二十女",
			  	".*氏"
				);
  private $default_count = 1000;
  public function __construct()
  {
    parent::__construct();
  }
  public function add_links_on_name_in_event()
  {
    $common_exp = "/".implode('|', $this->common_names)."/";
    //header('Content-Type: text/html; charset=utf-8');
    $db = new M_qin_users();
    $res = $db->get_users();
    $users = M_Tools::convert_mysql_results_to_array($res, 'id', 'realname');
    $links = array();
    $names = array();
    $i = 0;
    $from = isset($_REQUEST["from"]) ? $_REQUEST["from"] : 0;
    $count= isset($_REQUEST["count"]) ? $_REQUEST["count"] : $this->default_count;
    foreach($users as $id=>$name)
      {
	/* 跳过通用的名字，如长子、三女、刘氏 等无意义的名字，*/
	if (preg_match($common_exp, $name))
	  continue;

	$names[$i] = $name;
	$links[$i] = "<a href='/tree/index?userid=${id}'>${name}</a>（<a href='/tree/index?userid=${id}'>家谱</a>,<a href='/users/home?userid=${id}'>主页</a>,<a href='/users/album?userid=${id}'>相册</a>）";
	$i++;
      }

    $tbl = new M_qin_events();
    $i=0;
    foreach($users as $id=>$name)
      {
	if ($id < $from)
	    continue;

	print "@@@ id: ${id}, ${name}, count: $i<br/>";
	$events = $tbl->get_events($id);
	foreach($events as $event)
	  {
	    $str = $this->add_links($event["event"], $name, $names, $links);
	    //print ">>> ".$str."<br/>";
	    $tbl->edit($event["id"], array("event"=>$str));
	  }
	flush();
	ob_flush();
	if($i++ > $count) break;
      }

  }
  public function add_links($str, $name, $names, $links)
  {
    $length = 30;
    $offset = 0;

    $matched = array();
    // build expression
    while($offset< count($names))
      {
	$n = array_slice($names, $offset, $length);
	$offset += $length;
	$exp = "/".implode('|', $n)."/";
	$ret = preg_match_all($exp, $str, $matches);
	if ($ret)//$matches[0])
	  {
	    foreach($matches as $m)
	      if ($m[0] && $name != $m[0])
		$matched[] = $m[0];
	  }
      }
    $replace = array();
    $expr = array();
    foreach($matched as $k => $m)
      {
	$key = array_search($m, $names);
	//名字的前面不是‘>’（即不是连接<a href=''>xxx</a>）
	$expr[$k] = "/(?<!\>)$m/"; 
	$replace[$k] = $links[$key];
      }
    $str = preg_replace($expr, $replace, $str);
    $str = preg_replace($expr, $replace, $str);
    return $str;
  }
}
